package aynu.oracle.video.controller;

import aynu.oracle.video.pojo.Author;
import aynu.oracle.video.pojo.Category;
import aynu.oracle.video.pojo.FileInfo;
import aynu.oracle.video.pojo.Video;
import aynu.oracle.video.service.IVideoService;
import aynu.oracle.video.service.Impl.webUploader;

import aynu.oracle.video.util.VideoUtil;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * 控制层，调用业务层实现指定的效果
 * 该类，主要通过调用指定方法，实现文件上传
 */
@CrossOrigin	// 解决vue访问时的跨域问题
@RestController
@RequestMapping("/video")
public class FileUploadController {

	// 日志记录
	private final static Logger log = LoggerFactory.getLogger(FileUploadController.class);
	// type页面大小
	private static final int TYPE_PAGE_SIZE = 8;
	// all页面大小
	private static final int All_PAGE_SIZE = 10;
	// 热门页面大小
	private static final int HOT_PAGE_SIZE = 6;
	private String uploadFolder = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\file";	// 视频文件存放的路径
	@Value("D:\\文件\\Ideaworkspace\\video\\src\\main\\resources\\static\\file\\")
	private String coverPath;
	// webUploader对象，调用指定方法 完成文件上传
	@Autowired
	private webUploader wu;
	@Autowired
	private IVideoService videoService;
	// 视频的title属性
	private String videoTitle;

	/**
	 * 文件上传
	 * @param status 操作状态
	 * @param info 文件的部分信息
	 * @param file 文件
	 * @return string 结果集合
	 */
	@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
	public String fileUpload(String status, FileInfo info,Integer vid,String vpath,String suffix, @RequestParam(value = "file", required = false) MultipartFile file){
		if(file!=null) {
			videoTitle = file.getOriginalFilename();
		}
		// 当操作码为null时，表示从新上传
		if(status == null){	//文件上传
			if(file != null && !file.isEmpty()){	//验证请求不会包含数据上传，所以避免NullPoint这里要检查一下file变量是否为null
				try {
					//为上传的文件准备好对应的位置
					File target = wu.getReadySpace(info, this.uploadFolder);
					String s = String.valueOf(target);
					if(s.lastIndexOf('.')>=0){
						suffix = s.substring(s.lastIndexOf('.')+1);
					}
					if(target == null){
						return "{\"status\": 0, \"message\": \"" + wu.getErrorMsg() + "\"}";
					}
					file.transferTo(target);	//保存上传文件
					return "{\"status\": 1, \"path\": \"" + target.getName() + "\"}";
				}catch(IOException ex){
					log.error("数据上传失败", ex);
					return "{\"status\": 0, \"message\": \"数据上传失败\"}";
				}
			}
		}else{
			if(status.equals("md5Check")){	// 当操作码是 md5Check 时，用来进行秒传验证
//				System.out.println("秒传验证");
				return "{\"ifExist\": 0}";
			}else if(status.equals("chunkCheck")){	// 当操作码是 chunkCheck 时，用来进行分块验证
//				System.out.println("分块验证");
				//检查目标分片是否存在且完整
				if(wu.chunkCheck(this.uploadFolder + "/" + info.getName() + "/" + info.getChunkIndex(), Long.valueOf(info.getSize()))){
					return "{\"ifExist\": 1}";
				}else{
					return "{\"ifExist\": 0}";
				}
			}else if(status.equals("chunksMerge")){	// 当操作码是 chunksMerge 时，用来进行分块合并
//				System.out.println("分块合并");
				String path_time = wu.chunksMerge(info.getName(), info.getExt(), info.getChunks(), info.getMd5(), this.uploadFolder);
				if(path_time==null||"null".equals(path_time)){
					log.error("分片数量不足，无法合并");
					return "{\"status\": 0, \"message\": \"" + wu.getErrorMsg() + "\"}";
				}
				int t = path_time.lastIndexOf(" ");
				String path = path_time.substring(0,t);
				String time = path_time.substring(t+1);
				if(path == null){
					return "{\"status\": 0, \"message\": \"" + wu.getErrorMsg() + "\"}";
				}
				// 设置Video对象
				if(videoTitle.lastIndexOf(".")!=-1){
					videoTitle = videoTitle.substring(0,videoTitle.lastIndexOf("."));
				}
				String pic_path = path.substring(0,path.lastIndexOf(".")) + ".jpg";
				String release_time = VideoUtil.getNowDate();
				Video video = new Video(null, videoTitle, path,pic_path, time, 1, 1,1,0, release_time, 0,null);
				int i = videoService.insertVideo(video);
				if(i==0){
					return "{\"status\": 0, \"message\": \"" + wu.getErrorMsg() + "\"}";
				}
				return "{\"status\": 1, \"path\": \"" + path + "\", \"vid\": \""+video.getId()+"\", \"vpath\": \""
						+video.getVideoFilePath().substring(0,video.getVideoFilePath().lastIndexOf('.'))+"\"}";
			}
		}
		log.error("请求参数不完整");
		return "{\"status\": 0, \"message\": \"请求参数不完整\"}";
	}

	/**
	 * 上传者 放弃上传的视频文件，清除所有分片
	 * @param info 视频文件的部分信息
	 * @return string
	 */
	@RequestMapping("/clearChunks")
	public String clearChunks(FileInfo info){
//		System.out.println("info___"+info);
		String result = wu.chunksMerge(info.getName(), info.getExt(), info.getChunks(), info.getMd5(), this.uploadFolder);
//		System.out.println("clearChunks = "+result);
		return result;
	}

	/**
	 * 删除视频记录
	 * @param ids 视频ID
	 * @param videoFilePaths 对应的视频文件路径
	 * @param videoCoverPics 对应的封面文件路径
	 * @return int
	 */
	@RequestMapping("/removeVideoById")
	public int removeVideoById(Integer[] ids,String[] videoFilePaths,String[] videoCoverPics){
//		System.out.println(ids + " - " + videoFilePaths + " - " + videoCoverPics);
		if(ids.length>0){
			for (int i = 0; i <ids.length ; i++) {
				boolean b = wu.deleteVideoFile(uploadFolder + "\\" + videoFilePaths[i]);
				boolean b1 = wu.deleteVideoFile(uploadFolder + "\\" + videoCoverPics[i]);
				if(!b||!b1) return 0;
			}

			int row = videoService.deleteVideoById(ids);
//			System.out.println("b = "+b+"，b1 = "+b1+"，row = "+row);
			return row;
		}
		return 0;
	}

	/**
	 * 获取所有数据
	 * @return view 视图跳转
	 */
	@RequestMapping("/queryAll")
	public List<Video> queryAll(@RequestParam(defaultValue = "1") Integer index){
		List<Video> videos = videoService.selectAllVideo((index-1)*All_PAGE_SIZE,All_PAGE_SIZE);
		return videos;
	}

	/**
	 * 通过id获取一条记录
	 * @param id 用来获取某一条记录
	 * @return video对象
	 */
	@RequestMapping("/queryAllById")
	public Video queryAllById(Integer id){
		Video video = videoService.selectVideoById(id);
//		System.out.println(video);
		return video;
	}

	/**
	 * 获取热门推荐数据
	 * @return list
	 */
	@RequestMapping("/queryHots")
	public List<Video> queryHots(@RequestParam(defaultValue = "1") Integer index){
		return videoService.selectHotsVideo((index-1)*HOT_PAGE_SIZE,HOT_PAGE_SIZE);
	}

	/**
	 * 按照类别分页查询
	 * @param videoCategory 类别
	 * @param index 页码
	 * @return list
	 */
	@RequestMapping("/queryVideoByCategory")
	public List<Video> queryVideoByCategory(Integer videoCategory,@RequestParam(defaultValue = "1") Integer index) {
		List<Video> videos = videoService.selectVideoByCategory(videoCategory, (index-1)*TYPE_PAGE_SIZE, TYPE_PAGE_SIZE);
//		System.out.println(videos);
		return videos;
	}

	/**
	 * 按照作者分页查询
	 * @param videoAuthor 所属老师
	 * @param index 页码
	 * @return list
	 */
	@RequestMapping("/queryVideoByAuthor")
	public List<Video> queryVideoByAuthor(Integer videoAuthor,@RequestParam(defaultValue = "1") Integer index) {
		List<Video> videos = videoService.selectVideoByAuthor(videoAuthor, (index-1)*TYPE_PAGE_SIZE, TYPE_PAGE_SIZE);
//		System.out.println(videos);
		return videos;
	}

	/**
	 * 修改视频其他信息
	 * @param video 视频对象
	 * @return int
	 */
	@RequestMapping("/modifyVideoOtherInfo")
	public int modifyVideoOtherInfo(Video video) {
//		System.out.println(video);
		return videoService.updateVideoOtherInfo(video);
	}

	/**
	 * 按照用户查询没有被审核的视频
	 * @param videoUser 用户
	 * @param index 页码
	 * @return list
	 */
	@RequestMapping("queryVideoByUserAndNotAudio")
	public List<Video> queryVideoByUserAndNotAudio(Integer videoUser,@RequestParam(defaultValue = "1") Integer index) {
		List<Video> videos = videoService.selectVideoByUserAndNotAudio(videoUser, (index-1)*TYPE_PAGE_SIZE, TYPE_PAGE_SIZE);
//		System.out.println(videos);
		return videos;
	}

	/**
	 * 查询全部类别
	 * @return 图片类别的集合
	 */
	@RequestMapping("queryVideoAllCategory")
	public List<Category> queryVideoAllCategory(){
		List<Category> categories = videoService.selectVideoAllCategory();
//		System.out.println(categories);
		return categories;
	}

	/**
	 * 查询 老师 的类别
	 * @return list 老师类别的集合
	 */
	@RequestMapping("queryVideoAuthor")
	public List<Author> queryVideoAuthor(){
		List<Author> authors = videoService.selectVideoAuthor();
		return authors;
	}

	// 获取总数目
	@RequestMapping("/queryVideoCount")
	public int queryVideoCount(){
		return videoService.selectVideoCount();
	}

	// 根据用户ID获取总数目
	@RequestMapping("/queryVideoCountByVideoUser")
	public int queryVideoCountByVideoUser(Integer videoUser){
		return videoService.selectVideoCountByVideoUser(videoUser);
	}

	// 修改封面
	@RequestMapping("/modifyCoverPic")
	public int modifyCoverPic(Integer id, String videoCoverPic,MultipartFile file){
		String imgName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
		int i = videoService.updateCoverPic(id,imgName);
		if(i > 0){
			try {
				// 上传新封面
				file.transferTo(new File(coverPath + imgName));
				// 删除原封面
				if(videoCoverPic!=null&&videoCoverPic.length()>0) {
					File delFile = new File(coverPath+videoCoverPic);
					if(delFile.exists()){
						delFile.delete();
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return i;
	}

	// 批量审核
	@RequestMapping("/videoIsAudio")
	public int videoIsAudio(Integer[] ids){
//		for (Integer id :ids) {
//			System.out.println(id);
//		}

		int row = videoService.videoIsAudio(ids);
		return row;
	}


}